package fate.tlg;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.IOException;


public class TLGImageIO {
    private final TLGImage image;
    public TLGImageIO(TLGImage image) {
        this.image = image;
    }
    
    public BufferedImage asBufferedImage() {
        int colors = image.getColors();
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage buffer = new BufferedImage(width, height,
                colors == 4 ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
        byte[] bytes = image.getImageBuffer();
        int [] pixels = new int[bytes.length/colors];
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = (bytes[i * colors] & 0xff) | ((bytes[i * colors + 1] & 0xff) << 8) | ((bytes[i * colors + 2] & 0xff) << 16);
            if (colors == 4) {
                pixels[i] |= ((bytes[i * colors + 3] & 0xff) << 24);
            }
        }
        buffer.setRGB(0, 0, width, height, pixels, 0, width);
        return buffer;
    }

    public void asPNG(String path) throws IOException {
        ImageIO.write(asBufferedImage(), "PNG", new java.io.File(path));
    }

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        TLGImage image = new TLGDecoder("D:\\Projects\\Special\\libfate\\libfate-py\\1.tlg").getImage();
        BufferedImage i = new TLGImageIO(image).asBufferedImage();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
